<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑SDK文档"
    width="70%"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    class="edit-dialog"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="sdk-form"
    >
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="SDK大类" prop="sdkCategory">
              <el-select
                v-model="form.sdkCategory"
                placeholder="请选择或输入SDK大类"
                filterable
                allow-create
                @change="handleSdkCategoryChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in uniqueSdkOptions"
                  :key="item.sdkCategory"
                  :label="item.sdkCategory"
                  :value="item.sdkCategory"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="大类名称" prop="categoryName">
              <el-input
                v-model="form.categoryName"
                placeholder="请输入大类名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="方法" prop="method">
              <el-input v-model="form.method" placeholder="请输入方法" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="方法名" prop="methodName">
              <el-input v-model="form.methodName" placeholder="请输入方法名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="功能简介" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入功能简介"
          />
        </el-form-item>
        <el-form-item label="注意事项" prop="notes">
          <el-input
            v-model="form.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入注意事项"
          />
        </el-form-item>
        <el-form-item label="返回格式" prop="returnFormat">
          <el-select v-model="form.returnFormat" placeholder="请选择返回格式">
            <el-option label="Promise" value="promise" />
            <el-option label="Callback" value="callback" />
          </el-select>
        </el-form-item>
      </div>

      <div class="form-section">
        <h3 class="section-title">代码示例</h3>
        <el-form-item label="调用示例" prop="callExample">
          <MonacoEditor
            style="height: 200px; border-radius: 8px"
            v-model="form.callExample"
            language="javascript"
            :options="{ height: '200px', minimap: { enabled: false } }"
            placeholder="请输入调用示例代码"
          />
        </el-form-item>
        <el-form-item label="返回示例" prop="returnExample">
          <MonacoEditor
            style="height: 200px; border-radius: 8px"
            v-model="form.returnExample"
            language="json"
            :options="{ height: '200px', minimap: { enabled: false } }"
            placeholder="请输入返回示例代码"
          />
        </el-form-item>
      </div>

      <!-- 参数列表 -->
      <div class="form-section">
        <div class="section-header">
          <h3 class="section-title">参数列表</h3>
          <el-button type="primary" size="small" @click="addParam">
            <el-icon><Plus /></el-icon>
            添加参数
          </el-button>
        </div>
        <div class="param-list">
          <div
            v-for="(param, index) in form.params"
            :key="index"
            class="param-item"
          >
            <div class="param-header">
              <span class="param-index">参数 {{ index + 1 }}</span>
              <el-button
                type="danger"
                size="small"
                circle
                @click="removeParam(index)"
                class="remove-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-row :gutter="16">
              <el-col :span="6">
                <el-form-item
                  :prop="`params.${index}.paramName`"
                  :rules="{
                    required: true,
                    message: '参数名不能为空',
                    trigger: 'blur',
                  }"
                  label="参数名"
                >
                  <el-input v-model="param.paramName" placeholder="参数名" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  :prop="`params.${index}.paramType`"
                  :rules="{
                    required: true,
                    message: '参数类型不能为空',
                    trigger: 'blur',
                  }"
                  label="参数类型"
                >
                  <el-select v-model="param.paramType" placeholder="请选择参数类型">
                    <el-option label="String" value="string" />
                    <el-option label="Number" value="number" />
                    <el-option label="Boolean" value="boolean" />
                    <el-option label="Object" value="object" />
                    <el-option label="Array" value="array" />
                    <el-option label="Function" value="function" />
                    <el-option label="Date" value="date" />
                    <el-option label="RegExp" value="regexp" />
                    <el-option label="Promise" value="promise" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item
                  :prop="`params.${index}.isRequired`"
                  label="是否必填"
                >
                  <el-switch
                    v-model="param.isRequired"
                    inline-prompt
                    active-text="必填"
                    inactive-text="选填"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  :prop="`params.${index}.paramExample`"
                  label="参数示例"
                >
                  <el-input
                    v-model="param.paramExample"
                    placeholder="参数示例"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item
              :prop="`params.${index}.paramDesc`"
              :rules="{
                required: true,
                message: '参数描述不能为空',
                trigger: 'blur',
              }"
              label="参数描述"
            >
              <el-input
                v-model="param.paramDesc"
                type="textarea"
                :rows="2"
                placeholder="参数描述"
              />
            </el-form-item>
          </div>
          <div v-if="form.params.length === 0" class="empty-state">
            <el-empty description="暂无参数" :image-size="80" />
          </div>
        </div>
      </div>

      <!-- 枚举值列表 -->
      <div class="form-section">
        <div class="section-header">
          <h3 class="section-title">枚举值列表</h3>
          <el-button type="primary" size="small" @click="addEnum">
            <el-icon><Plus /></el-icon>
            添加枚举值
          </el-button>
        </div>
        <div class="enum-list">
          <div
            v-for="(enum_, index) in form.enums"
            :key="index"
            class="enum-item"
          >
            <div class="enum-header">
              <span class="enum-index">枚举 {{ index + 1 }}</span>
              <el-button
                type="danger"
                size="small"
                circle
                @click="removeEnum(index)"
                class="remove-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-row :gutter="16">
              <el-col :span="6">
                <el-form-item
                  :prop="`enums.${index}.key`"
                  :rules="{
                    required: true,
                    message: '枚举键不能为空',
                    trigger: 'blur',
                  }"
                  label="枚举键"
                >
                  <el-input v-model="enum_.key" placeholder="枚举键" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  :prop="`enums.${index}.value`"
                  :rules="{
                    required: true,
                    message: '枚举值不能为空',
                    trigger: 'blur',
                  }"
                  label="枚举值"
                >
                  <el-input v-model="enum_.value" placeholder="枚举值" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  :prop="`enums.${index}.category`"
                  :rules="{
                    required: true,
                    message: '分类不能为空',
                    trigger: 'blur',
                  }"
                  label="分类"
                >
                  <el-input v-model="enum_.category" placeholder="分类" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  :prop="`enums.${index}.referenceImage`"
                  label="参考图链接"
                >
                  <el-input
                    v-model="enum_.referenceImage"
                    placeholder="参考图链接"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-if="form.enums.length === 0" class="empty-state">
            <el-empty description="暂无枚举值" :image-size="80" />
          </div>
        </div>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" size="large">取消</el-button>
        <el-button
          type="primary"
          @click="submitForm"
          size="large"
          :loading="loading"
        >
          保存修改
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { ElMessage } from "element-plus";
import { Delete, Plus } from "@element-plus/icons-vue";
import { updateSdk } from "@/api/modules/ueSdk";
import MonacoEditor from "@/components/MonacoEditor.vue";

const props = defineProps({
  sdkOptions: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(["success"]);

const dialogVisible = ref(false);
const formRef = ref();
const loading = ref(false);

// 表单数据
const form = reactive({
  id: "",
  sdkCategory: "",
  categoryName: "",
  method: "",
  methodName: "",
  description: "",
  notes: "",
  callExample: "",
  returnExample: "",
  returnFormat: "promise",
  params: [],
  enums: [],
});

// 表单验证规则
const rules = {
  sdkCategory: [{ required: true, message: "请输入SDK大类", trigger: "blur" }],
  categoryName: [
    { required: true, message: "请输入大类名称", trigger: "blur" },
  ],
  method: [{ required: true, message: "请输入方法", trigger: "blur" }],
  methodName: [{ required: true, message: "请输入方法名", trigger: "blur" }],
  description: [{ required: true, message: "请输入功能简介", trigger: "blur" }],
};

// 打开弹窗并填充数据
const open = (data) => {
  if (data) {
    Object.assign(form, {
      id: data._id || "",
      sdkCategory: data.sdkCategory || "",
      categoryName: data.categoryName || "",
      method: data.method || "",
      methodName: data.methodName || "",
      description: data.description || "",
      notes: data.notes || "",
      callExample: data.callExample || "",
      returnExample: data.returnExample || "",
      returnFormat: data.returnFormat || "promise",
      params: data.params ? JSON.parse(JSON.stringify(data.params)) : [],
      enums: data.enums ? JSON.parse(JSON.stringify(data.enums)) : [],
    });
  }
  dialogVisible.value = true;
};

// 添加参数
const addParam = () => {
  form.params.push({
    paramName: "",
    paramType: "",
    isRequired: false,
    paramExample: "",
    paramDesc: "",
  });
};

// 移除参数
const removeParam = (index) => {
  form.params.splice(index, 1);
};

// 添加枚举值
const addEnum = () => {
  form.enums.push({
    key: "",
    value: "",
    category: "",
    referenceImage: "",
  });
};

// 移除枚举值
const removeEnum = (index) => {
  form.enums.splice(index, 1);
};

// 计算去重后的SDK选项
const uniqueSdkOptions = computed(() => {
  const uniqueCategories = [];
  const seen = new Set();
  
  props.sdkOptions.forEach(item => {
    if (item.sdkCategory && !seen.has(item.sdkCategory)) {
      seen.add(item.sdkCategory);
      uniqueCategories.push({
        sdkCategory: item.sdkCategory,
        categoryName: item.categoryName
      });
    }
  });
  
  return uniqueCategories;
});

// 处理SDK大类选择变化
const handleSdkCategoryChange = (value) => {
  // 查找对应的大类名称
  const selectedOption = uniqueSdkOptions.value.find(item => item.sdkCategory === value);
  if (selectedOption) {
    form.categoryName = selectedOption.categoryName;
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      // TODO: 调用API提交修改数据
      console.log("submit edit form:", form);
      updateSdk(form)
        .then((res) => {
          loading.value = false;
          console.log(res);
          ElMessage.success("修改成功");
          dialogVisible.value = false;
          // 触发success事件，通知父组件刷新数据
          emit('success', res.data);
        })
        .catch(() => {
          loading.value = false;
        });
    } else {
      console.error("表单验证失败:", fields);
    }
  });
};

// 暴露方法给父组件
defineExpose({
  open,
});
</script>

<style scoped>
.edit-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
  max-height: 70vh;
  margin: 15vh auto;
}

.edit-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  color: white;
  padding: 20px 24px;
  margin: 0;
}

.edit-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

.edit-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 20px;
}

.edit-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.sdk-form {
  max-height: calc(70vh - 140px);
  overflow-y: auto;
  padding: 24px;
  /* background: #fafbfc; */
}

.form-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e8eaec;
}

.section-title {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
  display: inline-block;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header .section-title {
  margin-bottom: 0;
}

.param-item,
.enum-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  border: 1px solid #e8eaec;
  transition: all 0.3s ease;
}

.param-item:hover,
.enum-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
}

.param-header,
.enum-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e8eaec;
}

.param-index,
.enum-index {
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
}

.remove-btn {
  width: 28px;
  height: 28px;
}

.param-list,
.enum-list {
  min-height: 60px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  /* background: #fafbfc; */
  border-top: 1px solid #e8eaec;
}

/* 表单项样式优化 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: #409eff;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-textarea__inner:hover) {
  border-color: #409eff;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
}

/* 滚动条样式 */
.sdk-form::-webkit-scrollbar {
  width: 6px;
}

.sdk-form::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.sdk-form::-webkit-scrollbar-thumb {
  background: #409eff;
  border-radius: 3px;
}

.sdk-form::-webkit-scrollbar-thumb:hover {
  background: #337ecc;
}
</style>
